package com.dhee.creditcardsystem.util;


import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

//import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 获取数据库连接
 *
 * @author 小逗
 */
@Component
public class DBUtil {

    public static String driver;

    private static String url;

    private static String user;

    private static String password;

    @Value("${spring.datasource.driver-class-name}")
    public void setDriver(String driver) {
        DBUtil.driver = driver;
    }
    @Value("${spring.datasource.url}")
    public void setUrl(String url) {
        DBUtil.url = url;
    }
    @Value("${spring.datasource.username}")
    public void setUser(String user) {
        DBUtil.user = user;
    }
    @Value("${spring.datasource.password}")
    public void setPassword(String password) {
        DBUtil.password = password;
    }

    public static Connection getConnection() throws ClassNotFoundException {
        Connection conn = null;
        PreparedStatement pstmt = null;
        Class.forName(driver);
        try {
            conn = DriverManager.getConnection(url, user, password);


        } catch (Exception e) {
            e.printStackTrace();
        }

        return conn;
    }


    public static void close(Connection conn, PreparedStatement pstmt) {
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void close(Connection conn, PreparedStatement pstmt, java.sql.ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        close(conn, pstmt);

    }

    public static void main(String[] args) throws ClassNotFoundException {
        System.out.println(DBUtil.getConnection());
    }


}
